import './assets/main.css'

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import http from './utils/http'  // 导入http模块
import axios from 'axios'

import App from './App.vue'
import router from './router'
// import { setupRouterGuards } from './router' // 命名导入
// Removed duplicate import of createPinia
import piniaPersistedstate from 'pinia-plugin-persistedstate';

// 配置axios默认URL和拦截器
axios.defaults.baseURL = import.meta.env.VITE_API_URL || 'http://localhost:8080';

// 检查token是否有效
const checkToken = () => {
  const token = localStorage.getItem('token');
  const expireTime = localStorage.getItem('tokenExpireTime');
  
  if (token && expireTime) {
    const now = new Date().getTime();
    if (now < parseInt(expireTime)) {
      // token未过期，设置到axios默认headers
      axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
      return true;
    } else {
      // token已过期，清除所有认证信息
      localStorage.removeItem('token');
      localStorage.removeItem('teacherId');
      localStorage.removeItem('teacherName');
      localStorage.removeItem('tokenExpireTime');
      delete axios.defaults.headers.common['Authorization'];
    }
  }
  return false;
};

// 在应用启动时检查token
checkToken();

// 请求拦截器，自动添加token到请求头
axios.interceptors.request.use(
  config => {
    // 每次请求前检查token
    if (checkToken()) {
      return config;
    }
    
    // 如果token无效且不是登录或注册请求，重定向到登录页
    if (!config.url.includes('/auth/login') && !config.url.includes('/auth/register')) {
      router.push('/login');
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器，处理认证失败
axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response && error.response.status === 401) {
      // token失效，清除认证信息并重定向到登录页
      localStorage.removeItem('token');
      localStorage.removeItem('teacherId');
      localStorage.removeItem('teacherName');
      localStorage.removeItem('tokenExpireTime');
      delete axios.defaults.headers.common['Authorization'];
      router.push('/login');
    }
    return Promise.reject(error);
  }
);

const app = createApp(App)

// 全局注册
app.config.globalProperties.$http = http;

const pinia = createPinia();
pinia.use(piniaPersistedstate);

app.use(pinia);
app.use(router);
app.use(ElementPlus);

// 初始化路由守卫
// setupRouterGuards() // 现在可以正确调用

// 挂载应用
app.mount('#app');
